
package jh.com.jhappbf.weight.collect;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.model.AbMenuItem;
import com.ab.util.AbDialogUtil;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.configs.Constant;
import jh.com.jhappbf.httputils.ExportHelper;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.model.CollectInputSettingModel;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.JsonHelper;
import jh.com.jhappbf.utils.PixAndDpUtil;
import jh.com.jhappbf.verify.ListPopAdapter;

/**
 * @author Administrator
 */
public class CollectWeigh extends AbActivity {
    private View mContentView;
    private View mErrorView;
    private Context mAppContext;
    private LinearLayout mHeaderLayout;
    private ListView mListView;
    private Button mTryAgain;
    private List<JSONObject> mData;
    private Button mTitleRightBtn;
    private List<String> mHeaderTitle;
    private Drawable mLeftDrawable;
    private int mColumnWidth;
    private AbLoadDialogFragment mDialogFragment = null;
    private CollectBaseAdapter mAdapter;
    private CollectInputSettingModel mSettingModel;
    private final int GETSETTING = 0X0001;
    private String mFlag;
    private String mTypes;
    private RelativeLayout mLayoutExport;
    private HorizontalScrollView mScrollView;
    private String methodName = "collectWeight";
    private AbTitleBar mAbTitleBar;
    private String mCollectType = "收货单位";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContentView = getLayoutInflater().inflate(R.layout.collect_input_list_activity, null);
        mErrorView = getLayoutInflater().inflate(R.layout.net_error_activity, null);
        setAbContentView(mContentView);
        Intent i = getIntent();
        mFlag = i.getStringExtra("flag");
        mSettingModel = i.getParcelableExtra("setting");

        mAbTitleBar = this.getTitleBar();
        switch (mFlag) {
            case "sale":
                methodName = "collectSale";
                mAbTitleBar.setTitleText("销售汇总");
                break;
            case "buy":
                mTypes = "采购";
                methodName = "collectBuy";
                mAbTitleBar.setTitleText("采购汇总");
                break;
            case "out":
                mTypes = "销售";
                methodName = "collectOut";
                mAbTitleBar.setTitleText("销售汇总");
                break;
            case "dao":
                mTypes = "内倒";
                methodName = "collectDao";
                mAbTitleBar.setTitleText("内导汇总");
                break;
            case "ling":
                mTypes = "零售";
                methodName = "collectLing";
                mAbTitleBar.setTitleText("零售汇总");
                break;
            default:
                mAbTitleBar.setTitleText("客户汇总");
                break;
        }
        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
        mAbTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mAbTitleBar.setLogoLine(R.mipmap.line);
        mAbTitleBar.setLogoOnClickListener(v -> {
            Intent i1 = new Intent();
            i1.putExtra("result", mSettingModel);
            setResult(RESULT_OK, i1);
            CollectWeigh.this.finish();
        });
        View rightViewMore = mInflater.inflate(R.layout.title_right_app_btn_view, null);
        mAbTitleBar.addRightView(rightViewMore);
        mTitleRightBtn = rightViewMore.findViewById(R.id.title_right_btn);
        initView();
    }

    // /初始化
    private void initView() {
        mAppContext = getApplicationContext();
        mHeaderLayout = mContentView.findViewById(R.id.collect_input_weight_title);
        mListView = mContentView.findViewById(R.id.collect_input_weight_listView);
        mScrollView = mContentView.findViewById(R.id.collect_weight_hscroll);
//        mAdapter = new CollectBaseAdapter();
        mData = new ArrayList<>();
        mListView.addFooterView(View.inflate(this, R.layout.listview_footer, null));
//        mListView.setAdapter(mAdapter);
        mTryAgain = mErrorView.findViewById(R.id.network_error_btn);
        mLayoutExport = mContentView.findViewById(R.id.collect_weight_export_excel_layout);
        setExportPosition();
        mHeaderTitle = new ArrayList<>();
        mLeftDrawable = ContextCompat.getDrawable(this, R.mipmap.table_line);
        mLeftDrawable.setBounds(0, 0, mLeftDrawable.getMinimumWidth(), mLeftDrawable.getMinimumHeight());
        mColumnWidth = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 55, getResources().getDisplayMetrics());
        mTryAgain.setOnClickListener(v -> {
            setAbContentView(mContentView);
            refresh();
        });

        mTitleRightBtn.setOnClickListener(v -> {
            Intent i = new Intent(CollectWeigh.this, CollectSetting.class);
            i.putExtra("flag", "input");
            i.putExtra("setting", mSettingModel);
            startActivityForResult(i, GETSETTING);
        });

        mLayoutExport.setOnClickListener(v -> {
            String url = Constant.ServerPath + "outPutFile/collect/" + State.mAccount + mTypes + ".xls";
            new ExportHelper(mDialogFragment, url, CollectWeigh.this, mTypes + "汇总").export();
        });
//        setDropList();
        refresh();
    }

    /**
     * 设置标题下拉列表
     */
    private void setDropList() {
        mAbTitleBar.setTitleTextBackgroundResource(R.drawable.drop_down_selector);
        View v = getLayoutInflater().inflate(R.layout.list_pop, null);
        final ListView listView = v.findViewById(R.id.pop_list);
        final List<AbMenuItem> data = new ArrayList<>();
//        data.add(new AbMenuItem("单位货名汇总"));
        data.add(new AbMenuItem("货名汇总"));
        ListPopAdapter mListPopAdapter = new ListPopAdapter(this, data, R.layout.item_list_pop);
        listView.setAdapter(mListPopAdapter);
        mAbTitleBar.setTitleTextDropDown(v);
        mAbTitleBar.setTitleText(data.get(0).getText());
        listView.setOnItemClickListener((parent, view, position, id) -> {
            mAbTitleBar.setTitleText(data.get(position).getText());
            mCollectType = data.get(position).getText();
            mAbTitleBar.hideWindow();
            refresh();
        });
    }

    private void setExportPosition() {
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        mLayoutExport.measure(w, h);
        int width = mLayoutExport.getMeasuredWidth();
        int height = mLayoutExport.getMeasuredHeight();
        int screenWidth = PixAndDpUtil.getScreenWidth(getApplicationContext());
        int screenHeight = PixAndDpUtil.getScreenHeight(getApplicationContext());
        float pointx = (screenWidth - width - PixAndDpUtil.dp2px(15, getApplicationContext()));
        float pointy = (screenHeight - height - PixAndDpUtil.dp2px(100, getApplicationContext()));
        mLayoutExport.setX(pointx);
        mLayoutExport.setY(pointy);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == GETSETTING) {
            mSettingModel = data.getParcelableExtra("result");
            if (mSettingModel != null) {
                refresh();
            }
        }
    }

    ///刷新
    private void refresh() {
        mAdapter = null;
        mAdapter = new CollectBaseAdapter();
        mDialogFragment = AbDialogUtil.showLoadDialog(CollectWeigh.this, R.mipmap.ic_load, "查询中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(() -> getData(mSettingModel));
    }

    // 获取数据
    private void getData(CollectInputSettingModel model) {

//        if (mFlag.equals("buy") && "货名汇总".equals(mCollectType)) {
//            methodName ="collectBuy2";
//        }else if(mFlag.equals("buy") && "单位货名汇总".equals(mCollectType)){
//            methodName ="collectBuy";
//        }
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("startTime");
        param.add("endTime");
        param.add("cargoname");
        param.add("receiver");
        param.add("sender");
        param.add("user");
        param.add("company");

        if (model == null) {
            Date date = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            String todayDate = format.format(date);
            String end = todayDate + " 23:59:59";
            String start = todayDate + " 00:00:00";
            value.add(start);
            value.add(end);
            value.add("");
            value.add("");
            value.add("");

        } else {
            value.add(model.getStartTime());
            value.add(model.getEndTime());
            value.add(model.getCargoname());
            value.add(model.getReceiver());
            value.add(model.getSender());
        }

        value.add(State.mAccount);
        value.add(getCompany());
        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(CollectWeigh.this);
            if (mDialogFragment != null) {
                mDialogFragment.dismiss();
            }
            List<JSONObject> newListData = JsonHelper.getJsonObjects(response);
            if (newListData != null) {
                mHeaderTitle = new ArrayList<>();
                if (newListData.size() > 0) {
                    String[] head = newListData.get(0).optString("alias").split(",");
                    mHeaderTitle = Arrays.asList(head);
                    makeHead();
                }
                mData.clear();
                mData.addAll(newListData);
                mListView.setAdapter(mAdapter);
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(CollectWeigh.this);
            if (mDialogFragment != null) {
                mDialogFragment.dismiss();
            }
            setAbContentView(mErrorView);
            mData.clear();
            mAdapter.notifyDataSetChanged();
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName, param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
    }
    private String getCompany() {
        SharedPreferences preferences = getSharedPreferences("caption", MODE_PRIVATE);
        return preferences.getString("company", "");
    }
    // 生成表头
    private void makeHead() {
        mHeaderLayout.removeAllViews();
        for (int index = 0; index < mHeaderTitle.size(); index++) {
            TextView textView = new TextView(CollectWeigh.this);
            setColumnWidth(mHeaderTitle.get(index), textView);
            textView.setTextColor(Color.BLACK);
            textView.setGravity(Gravity.CENTER);
            textView.setCompoundDrawables(mLeftDrawable, null, null, null);
            textView.setPadding(1, 1, 1, 1);
            textView.setId(index);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
            textView.setText(mHeaderTitle.get(index));
            mHeaderLayout.addView(textView);
        }
    }


    private void setColumnWidth(String columnName, TextView textView) {
        switch (columnName) {
            case "发货单位":
            case "收货单位":
                textView.setWidth(mColumnWidth * 3);
                break;
            case "货名":
                textView.setWidth(mColumnWidth * 2);
                break;
            default:
                textView.setWidth((int) (mColumnWidth * 1.5));
                break;
        }
    }

    private class CollectBaseAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public Object getItem(int position) {
            return mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressLint("NewApi")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TableLayout tableLayout;
            if (convertView == null) {
                tableLayout = new TableLayout(CollectWeigh.this);
                TableRow tableRow = new TableRow(CollectWeigh.this);
                Drawable mItemSelect = ContextCompat.getDrawable(CollectWeigh.this, R.drawable.list_item_bg);
                tableRow.setBackground(mItemSelect);
                tableRow.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
                for (int index = 0; index < mHeaderTitle.size(); index++) {
                    TextView textView = new TextView(CollectWeigh.this);
                    setColumnWidth(mHeaderTitle.get(index), textView);
                    textView.setTextColor(Color.BLACK);
                    textView.setGravity(Gravity.CENTER);
                    textView.setCompoundDrawables(mLeftDrawable, null, null, null);
                    textView.setPadding(1, 0, 1, 0);
                    textView.setId(index);
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                    tableRow.addView(textView);
                }
                tableLayout.addView(tableRow);
                convertView = tableLayout;
                convertView.setTag(tableLayout);
            } else {
                tableLayout = (TableLayout) convertView.getTag();
            }

            JSONObject data = mData.get(position);
            String content;
            for (int index = 0; index < mHeaderTitle.size(); index++) {
                TextView txt = tableLayout.findViewById(index);
                if (txt == null) {
                    continue;
                }
                content = data.optString(mHeaderTitle.get(index));
                if ("null".equals(content)) {
                    content = "";
                }
                txt.setText(content);
            }
            return convertView;
        }
    }

    @Override
    public void onBackPressed() {
        finish();
    }
}
